package com.luqili.utils.pub.crypto;

import org.apache.commons.codec.binary.Hex;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

public class FileHash {

    public static String hashMd2(File file) {
        return hashType(file, "MD2");
    }

    /**
     * 求文件的Md5值
     *
     * @param file
     * @return
     */
    public static String hashMd5(File file) {
        return hashType(file, "MD5");
    }

    public static String hashSHA1(File file) {
        return hashType(file, "SHA-1");
    }

    public static String hashSHA256(File file) {
        return hashType(file, "SHA-256");
    }

    public static String hashSHA512(File file) {
        return hashType(file, "SHA-512");
    }

    /**
     * 求指定类型的HASH
     *
     * @param file
     * @param type {@link https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#MessageDigest}
     * @return
     */
    private static String hashType(File file, String type) {
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            MessageDigest md = MessageDigest.getInstance(type);
            byte[] bs = new byte[1024];
            int len = 0;
            while ((len = fin.read(bs)) > -1) {
                md.update(bs, 0, len);
            }
            byte[] r = md.digest();

            return Hex.encodeHexString(r);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (Exception e) {
                }
            }
        }
    }

}
